package com.yuji.aacar.core.cores.services;

import com.yuji.aacar.core.cores.utils.LogUtil;
import com.yuji.aacar.core.mvvm.appbase.CoreBaseViewModel;
import com.yuji.aacar.net.core.HttpManager;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;



/**
 * <li>Description:<li/>
 * <br>服务层:<br/>
 * <br>1.所有UI与网络及数据层的交互需要调用服务层接口<br/>
 * <br>2.耗时操作需要配合TaskPool完成<br/>
 * <br>3.服务接口均返回ServiceResponse对象，对返回结果进行包装<br/>
 */


public class CoreServiceMediator {

    public final static String PLATEFORM = "android";//设备平台
    public static String USER_TYPE = "0";//用户来自电商主站应用
    public final static String ACCOUNT_TYPE = "2";//手机注册
    public final static String EMAIL_AUTH_URL = "";//使用邮箱注册账号时的验证URL，手机注册传空
    public final static String CLIENT_ID = "clientId";//设备注册获得的id

    //    public static String pmfUrl = CoreENVConfig.xmlParser == null ? "" : CoreENVConfig.xmlParser.getPMFURL();

    /**************************** 公共接口 ****************************/

    public static final String GET_VERSION="getVersion";//获取版本号接口，判断是否需要升级和当前版本
    /**
     * 返回码定义
     */
    public final static int Service_Return_Success = 0;
    public final static String Service_Return_Success_Desc = "请求成功";
    public final static int Service_Return_Error = 90001;
    public final static String Service_Return_Error_Desc = "请求失败";
    // 网络异常
    public final static int Service_Return_RequestTimeOut = 90003;
    public final static String Service_Return_RequestTimeOut_Desc = "请求超时";


    public final static int kOpenAPIURLError = 60101001;   //OpenApi 调用 URL 不符合规范
    //时间戳超时

    public final static String SERVICE_REGISTER = "doRegister"; // 用户注册

    /**
     * 所有api的方法汇总
     */
    private static ConcurrentHashMap<Object, HashMap<String, Method>> apiMap = new ConcurrentHashMap<Object, HashMap<String, Method>>();
    /**
     * 所有框架调用的业务的API  //所有api的方法
     */
    private static ConcurrentHashMap<String, Method> apiMethodMap = new ConcurrentHashMap<String, Method>(128);    //所有api的方法

    /**
     * 所有业务的API
     */
    public static ArrayList<Class> apis = new ArrayList<>();
    private static ArrayList<Object> apiServiceList; //保存serviceApi的方法


    /**
     * 所有业务的请求对象
     */
    public static ArrayList<CoreServiceMediator> serviceMediatorList = new ArrayList<>();

    /**
     * 所有serviceMediator的请求
     */
    public static ConcurrentHashMap<CoreServiceMediator, ArrayList<Method>> servicesMap = new ConcurrentHashMap<CoreServiceMediator, ArrayList<Method>>();


    /**
     * Http头域信息,在Application中配置并设置相关值
     */
    //	public static Head httpHeader = new Head();

    /**
     * 方法映射 用于TaskPool
     *
     * @return
     */
    public ConcurrentHashMap<String, Method> getMethodMap() {
        return apiMethodMap;
    }

    public static Method getApiMethodByName(String strName) {
        return apiMethodMap.get(strName);
    }

    protected CoreServiceMediator() {
    }

    protected CoreServiceMediator(CoreBaseViewModel viewModel) {

    }

    /**
     * 初始化应用框架里面所有的api方法
     */
    public static void initAppAPIs(Class api) {
        if (!apis.contains(api)) {
            apis.add(api);
            resetAPIMaps(api);
        }
    }

    @Field_Method_Parameter_Annotation(args = {"request"})
//    public static CoreVersionRequest getVersion(CoreVersionRequest request){
//        request.setCode(100001);//获取版本号， 判断是否需要升级
//        return request;
//    }

    /**
     * 重置API相关的map
     */
    protected static void resetAPIMaps(Class api) {

        if (apiServiceList == null) {
            apiServiceList = new ArrayList<>(128);
        }
        if (!apis.isEmpty()) {
            for (int i = 0; i < apis.size(); i++) {
                Object service = HttpManager.getHttpService(apis.get(i), null);
                if (!apiServiceList.contains(service.getClass().getSimpleName())) {
                    apiServiceList.add(service.getClass().getSimpleName());
                    Method[] methods = service.getClass().getMethods();
                    HashMap<String, Method> temp = new HashMap<>();
                    for (int j = 0; j < methods.length; j++) {
                        if (!apiMethodMap.containsValue(methods[j]))
                            temp.put(methods[j].getName(), methods[j]);
                        apiMethodMap.put(methods[j].getName(), methods[j]);
                    }
                    apiMap.put(service, temp);
                }
            }
        }
        Object baseService = HttpManager.getHttpService(CoreBaseApi.class, null);
        if (null != baseService){
            if (!apiServiceList.contains(baseService.getClass().getSimpleName())) {
                apiServiceList.add(baseService.getClass().getSimpleName());
                Method[] baseMethods = baseService.getClass().getMethods();
                HashMap<String, Method> temp = new HashMap<>();
                for (int i = 0; i < baseMethods.length; i++) {
                    if (!apiMethodMap.containsValue(baseMethods[i])) {
                        //public final rx.Observable $Proxy4.getHomePageInfo(consumer.ttpc.com.httpmodule.bean.HttpCoreBaseRequest)
                        //public final rx.Observable $Proxy4.getImg(java.lang.String)
                        //public final rx.Observable $Proxy4.getList(com.ttp.android_core.bean.requestbean.BiddingHallChildRequest)
                        temp.put(baseMethods[i].getName(), baseMethods[i]);
                        apiMethodMap.put(baseMethods[i].getName(), baseMethods[i]);
                    }
                }
                apiMap.put(baseService, temp);
            }
        }


        LogUtil.e("[CoreServiceMediator size]---serviceList---", apiServiceList.size());
        LogUtil.e("[CoreServiceMediator size]---methodMaps---", apiMethodMap.size());
        LogUtil.e("[CoreServiceMediator size]---apiMap---", apiMap.size());
        LogUtil.e("[CoreServiceMediator size]---apiMap---", apiMap);
    }

    public static Object getHttpServiceApiByMethod(String methodName) {
        if (!apiMap.isEmpty()) {
            for (Object key : apiMap.keySet()) {
                HashMap<String, Method> values = apiMap.get(key);
                for (String key2 : values.keySet()) {
                    Method method = values.get(key2);
                    String name = method.getName();
                    if (name.contentEquals(methodName)) {
                        return key;
                    }
                }
            }
        }
        return null;
    }


    /**
     * 初始化应用框架里面所有的servicemediator方法
     */
    public static void initAppServicesMediators(CoreServiceMediator api) {
        if (!serviceMediatorList.contains(api)) {
            serviceMediatorList.add(api);
            resetServiceMediatorMaps();
        }
    }

    /**
     * 重置servicemediator相关的map
     */
    protected static void resetServiceMediatorMaps() {

        if (!serviceMediatorList.isEmpty()) {
            for (int i = 0; i < serviceMediatorList.size(); i++) {
                CoreServiceMediator mediator = serviceMediatorList.get(i);
                ArrayList<Method> methodList = new ArrayList<>();
                Method[] methods = mediator.getClass().getMethods();
                for (int j = 0; j < methods.length; j++) {
                    methodList.add(methods[j]);
                }
                servicesMap.put(mediator, methodList);
            }
            //TODO coreservicemediator的方法
        }
        LogUtil.e("[CoreServiceMediator servicesMap]---servicesMap---", servicesMap);
        LogUtil.e("[CoreServiceMediator servicesMap]---methodMaps---", servicesMap.size());
    }

    public static HashMap<CoreServiceMediator, Method> getServiceMediatorAndMethodByMethod(String method) {
        if (!servicesMap.isEmpty()) {
            HashMap<CoreServiceMediator, Method> result = new HashMap<>();
            for (CoreServiceMediator key : servicesMap.keySet()) {
                ArrayList<Method> methods = servicesMap.get(key);
                for (int i = 0; i < methods.size(); i++) {
                    Method value = methods.get(i);
                    String name = value.getName();
                    if (name.contentEquals(method)) {
                        result.put(key, value);
                        return result;
                    }
                }
            }
        }
        return null;
    }
}
